import {getLogin} from '@/api/login'
import {getUserInfo} from "@/api/user";

const user = {
    state: {
        token: localStorage.getItem("authorization"),
        name: '',
        avatar: '',
        roles: [],
        permissions: []
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
        }
    },

    actions: {
        // 登录
        Login({commit}, userInfo) {
            return new Promise((resolve, reject) => {
                getLogin("/doLogin", userInfo).then(res => {
                    localStorage.setItem("authorization", res.data);
                    commit('SET_TOKEN', res.data);
                    resolve(res);
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetInfo({commit}) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    const user = res.data;
                    commit('SET_NAME', user.loginName);
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 退出系统
        // LogOut({commit, state, dispatch}) {
        //   return new Promise((resolve, reject) => {
        //     logout(state.token).then(() => {
        //       commit('SET_TOKEN', '');
        //       commit('SET_ROLES', []);
        //       commit('SET_PERMISSIONS', []);
        //       removeToken();
        //
        //       // reset visited views and cached views
        //       // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        //       dispatch('tagsView/delAllViews', null, { root: true });
        //
        //       resolve()
        //     }).catch(error => {
        //       reject(error)
        //     })
        //   })
        // },

        // 前端 登出
        FedLogOut({commit}) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '');
                localStorage.removeItem('authorization');
                resolve()
            })
        }
    }
};

export default user
